package carcassonne.server.websocket.controller;

import carcassonne.game.GameSetupInfo;
import carcassonne.game.player.PlayColorInfo;
import carcassonne.game.player.Player;
import carcassonne.lobby.Room;
import carcassonne.server.ioc.Controller;
import carcassonne.server.ioc.RequestMapping;
import carcassonne.server.ioc.WebSocketMessageHandler;
import carcassonne.server.websocket.WebsocketContext;

@Controller
@RequestMapping(value = "lobby")
public class LobbyController {

    @WebSocketMessageHandler(path = "/get_players")
    public void GetPlayers(WebsocketContext context) {
//        String roomID = context.GetString();
//        if (StringUtils.IsNullOrEmpty(roomID)) {
//            context.Error("error room id: " + roomID);
//            return;
//        }
//        Room room = RoomManager.GetInstance().GetRoom(roomID);
//        if (room == null) {
//            context.Error("error room id: " + roomID);
//            return;
//        }
        context.Write("/lobby/setup_players", context.room.GetPlayerInfos());
    }

    static class PlayerSitDownInfo
    {
        public String id;
        public int from;
        public int to;
    }

    @WebSocketMessageHandler(path = "/player_sit_down")
    public void PlayerSitDown(WebsocketContext context) {
        Room room = context.room;
        PlayerSitDownInfo info = context.GetObject(PlayerSitDownInfo.class);
        room.PlayerSitDown(context.channel, info.id, info.from, info.to);
    }

    @WebSocketMessageHandler(path = "/set_player_color")
    public void SetPlayerColor(WebsocketContext context) {
        Room room = context.room;
        PlayColorInfo info = context.GetObject(PlayColorInfo.class);
        Player player = room.SetPlayerColor(info.seat, info.color);
        if (player == null) {
            context.Error("no match player with seat " + info.seat);
        } else {
            room.NotifyAll("/lobby/update_competitor", player.GetPlayerInfo());
        }
    }

    @WebSocketMessageHandler(path = "/player_ready")
    public void PlayerReady(WebsocketContext context) {

    }

    @WebSocketMessageHandler(path = "/start_game")
    public void StartGame(WebsocketContext context) {
        if (!context.IsHost()) return;
        Room room = context.room;
        GameSetupInfo gameSetupInfo = context.GetObject(GameSetupInfo.class);
        if (gameSetupInfo == null) {
            context.Error("error with game setup info");
            return;
        }
        room.StartGame(gameSetupInfo);
        context.room.NotifyExcept(context.raw);
    }
}
